package com.ruoyi.ruoyictmanage.mapper;

import com.ruoyi.ruoyictmanage.domain.entity.Line;
import com.ruoyi.ruoyictmanage.domain.entity.LinkUser;
import org.apache.ibatis.annotations.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Mapper
public interface LineMapper {

    @Select("select * from line where line_id=#{line_id}")
    Line selectLineById(@Param("line_id")int lineId);

    @Select("select * from line")
    List<Line> getLineList();


    @Select("select user_id,user_name from sys_user where dept_id=#{dept_id}")
    List<LinkUser> UserIdUserNameByDeptId(@Param("dept_id")Long deptId);


    @Select("select line_id from linelink where user_id=#{userId}")
    List<Integer> getUserLinkLine(Long userId);


    // Method 1: Create temporary table
    @Update("CREATE TEMPORARY TABLE IF NOT EXISTS temp_selected (line_id INT, user_id BIGINT)")
    void createTempTable();

    // Method 2: Insert selected parameters
    @Insert({
            "<script>",
            "INSERT INTO temp_selected (line_id, user_id) VALUES ",
            "<foreach collection='list' item='item' separator=','>",
            "(#{item}, #{userId})",
            "</foreach>",
            "</script>"
    })
    void insertSelectedParams(@Param("list") List<Integer> lineList,@Param("userId") Long userId);

    // Method 3: Execute transaction
    @Transactional
    default void updateLineLinkState(List<Integer> lineList, Long userId) {
        createTempTable();
        insertSelectedParams(lineList,userId);

        // 3.1 Update unselected items to state 0
        updateUnselectedItems(userId);

        // 3.2 Upsert selected items
        upsertSelectedItems();

        // Cleanup (optional)
        cleanTempTable();
    }

    @Update("UPDATE linelink t LEFT JOIN temp_selected s ON t.line_id = s.line_id AND t.user_id = s.user_id " +
            "SET t.state = 0 WHERE t.user_id = #{userId} AND s.line_id IS NULL")
    void updateUnselectedItems(@Param("userId") Long userId);

    @Insert("INSERT INTO linelink (line_id, user_id, state) " +
            "SELECT s.line_id, s.user_id, 1 FROM temp_selected s " +
            "ON DUPLICATE KEY UPDATE state = 1")
    void upsertSelectedItems();

    @Update("DROP TEMPORARY TABLE IF EXISTS temp_selected")
    void cleanTempTable();

    @Select("select l.* from line l inner join linelink k on  l.line_id=k.line_id where k.user_id=#{user_id}")
    List<Line> getLineListByLoginId(@Param("user_id") Long userId);
}
